import { Typography } from "antd";
import { nanoid } from "nanoid";
import React, { useCallback } from "react";
import { useDispatch } from "react-redux";
import { addComponent } from "../../../store/componentsReducer";
import {
  componentConfGroup,
  ComponentConfType,
} from "../../components/QuestionComponents";
import styles from "./ComponentLib.module.scss";
import useGetPageInfo from "../../../hooks/useGetPageInfo"; // 添加引入
import classNames from "classnames";

function genComponent(c: ComponentConfType, isPublished: boolean) {
  const dispatch = useDispatch();
  const { title, type, Component, defaultProps } = c;

  const handleClick = useCallback(() => {
    // 当问卷已发布时，禁用添加组件功能
    if (isPublished) return;

    dispatch(
      addComponent({
        id: "temp--" + nanoid(6),
        title,
        type,
        props: defaultProps,
      })
    );
  }, [isPublished]);

  const wrapperDefaultClassName = styles.wrapper;
  const hoverClassName = styles.hover;
  const disabledClassName = styles.disabled;
  const wrapperClassName = classNames({
    [wrapperDefaultClassName]: true,
    [hoverClassName]: !isPublished, // 已发布时，禁用hover
    [disabledClassName]: isPublished, // 已发布时，添加禁用样式
  });

  return (
    <div key={type} className={wrapperClassName} onClick={handleClick}>
      <div className={styles.component}>
        <Component />
      </div>
    </div>
  );
}

export const ComponentLib: React.FC = () => {
  const { isPublished } = useGetPageInfo(); // 获取发布状态

  return (
    <>
      {componentConfGroup.map((group, index) => {
        const { groupId, groupName, components } = group;
        return (
          <div
            key={groupId}
            style={{
              userSelect: "none",
            }}
          >
            <Typography.Title
              level={3}
              style={{
                color: "#1677ff",
                fontSize: "18px",
                marginTop: index > 0 ? "20px" : "0",
                marginBottom: "20px",
              }}
            >
              {groupName}
            </Typography.Title>
            <div>{components.map((c) => genComponent(c, isPublished))}</div>
          </div>
        );
      })}
    </>
  );
};
